package com.bjgzy.courselive.mvp.presenter;

import android.app.Application;
import android.os.Handler;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bjgzy.courselive.mvp.contract.OrderPayContract;
import com.blankj.utilcode.util.SPUtils;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.AliOrderData;
import com.eduhzy.ttw.commonsdk.entity.AliPayResult;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.entity.OrderPayStatus;
import com.eduhzy.ttw.commonsdk.entity.RightOrderInfo;
import com.eduhzy.ttw.commonsdk.entity.WXPayData;
import com.eduhzy.ttw.commonsdk.utils.Utils;
import com.eduhzy.ttw.commonsdk.utils.WXPay;
import com.eduhzy.ttw.commonsdk.utils.alipay.OrderInfoUtil2_0;
import com.google.gson.Gson;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * @author xubo
 * @date 2018-8-3 13:44:39
 */
@ActivityScope
public class OrderPayPresenter extends BasePresenter<OrderPayContract.Model, OrderPayContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    Gson mGson;

    @Inject
    public OrderPayPresenter(OrderPayContract.Model model, OrderPayContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }


    public void getAliPayOrderInfo(String productType, String body, int payYuan, int shopId, long orderId) {
        QMUITipDialog dialog = RxUtil.showLoading(mRootView.getActivity(), "请稍后···");

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("title", productType);
        map.put("body", body);
        map.put("shopId", 1);
        map.put("orderId", orderId);
        map.put("price", payYuan);
        mModel.getAliPayOrderInfo(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> dialog.show())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(dialog::dismiss)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                //这里交个外部传入的observer来处理对应的结果
                .subscribe(new ErrorHandleSubscriber<CommonData<AliOrderData>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<AliOrderData> commonData) {
                        if (commonData.isResult()) {
                            gotoAlipay(commonData, orderId);
                        } else {
                            if (commonData.getMessageCode() == 150003) {
                                getOrderPayStatus(String.valueOf(orderId));
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }
                });

    }

    private void gotoAlipay(CommonData<AliOrderData> commonData, long orderId) {
        Observable.create((ObservableOnSubscribe<Map<String, String>>) emitter -> {
            String orderInfo = OrderInfoUtil2_0.buildOrderParam(OrderInfoUtil2_0.buildOrderParamMap(commonData.getData().getOrderInfo()));
            Map<String, String> map = new PayTask(mRootView.getActivity()).payV2(orderInfo, true);
            emitter.onNext(map);
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<Map<String, String>>(mErrorHandler) {
                    @Override
                    public void onNext(Map<String, String> map) {
                        AliPayResult result = new AliPayResult(map);
                        switch (result.getResultStatus()) {
                            case "9000":
//                                AliPayResponse response = mGson.fromJson(result.getResult(), AliPayResponse.class);
//                                orderPaid(String.valueOf(orderId), response.getAlipay_trade_app_pay_response().getTrade_no(), "1");
                                QMUITipDialog dialog = RxUtil.showLoading(mRootView.getActivity(), "正在查询支付状态···");
                                dialog.show();
                                new Handler().postDelayed(() -> {
                                    dialog.dismiss();
                                    mRootView.paySuccess();
                                    mRootView.killMyself();
                                }, 3000);
                                break;
                            case "8000":
                                mRootView.showMessage("正在处理中");
                                break;
                            case "4000":
                                mRootView.showMessage("订单支付失败");
                                break;
                            case "5000":
                                mRootView.showMessage("重复请求");
                                break;
                            case "6001":
                                mRootView.showMessage("已取消支付");
                                break;
                            case "6002":
                                mRootView.showMessage("网络连接出错");
                                break;
                            case "6004":
                                mRootView.showMessage("正在处理中");
                                break;
                            default:
                                mRootView.showMessage("支付失败");
                                break;
                        }
                    }
                });

    }

    public void saveRightOrder(int internalId) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("resId", internalId);
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        mModel.saveRightOrder(map)
                .compose(RxUtil.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<List<RightOrderInfo>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<RightOrderInfo>> commonData) {
                        if (commonData.isResult()) {
                            mRootView.update(commonData.getData().get(0));
                        } else {
                            mRootView.showMessage("该课程已下过单，即将跳转到订单页面");
                            Utils.navigationWithTitle(RouterHub.COURSELIVE_MINEORDERACTIVITY, Constants.MINEORDER);
                            mRootView.killMyself();
                        }
                    }
                });
    }

    public void getWxPayOrderInfo(String productType, String body, int payYuan, int shopId,
                                  long orderId) {
        QMUITipDialog dialog = RxUtil.showLoading(mRootView.getActivity(), "请稍后···");
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("title", productType);
        map.put("body", body);
        map.put("shopId", 1);
        map.put("orderId", orderId);
        map.put("price", payYuan);
        mModel.getWxPayOrderInfo(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    dialog.show();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(dialog::dismiss)
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<WXPayData>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<WXPayData> commonData) {
                        if (commonData.isResult()) {
                            payByWeChat(commonData.getData().getOrderInfo(), commonData.getData().getOrderId());
                        }
                    }
                });

    }


    public void payByWeChat(WXPayData.OrderInfoBean wxOrdersBean, String orderId) {
        WXPay.getInstance().doPay(wxOrdersBean.toString(), new WXPay.WXPayResultCallBack() {
            @Override
            public void onSuccess() {
//                mRootView.showPayLoading(false);
//                getOrderPayStatus(orderId);
                QMUITipDialog dialog = RxUtil.showLoading(mRootView.getActivity(), "正在查询支付状态···");
                dialog.show();
                new Handler().postDelayed(() -> {
                    dialog.dismiss();
                    mRootView.paySuccess();
                    mRootView.killMyself();
                }, 3000);

            }

            @Override
            public void onError(int error_code) {
//                mRootView.showPayLoading(false);
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:
                        Toast.makeText(mRootView.getActivity(), "未安装微信或微信版本过低", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY_PARAM:
                        Toast.makeText(mRootView.getActivity(), "参数错误", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY:
                        Toast.makeText(mRootView.getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onCancel() {
//                mRootView.showPayLoading(false);
                Toast.makeText(mRootView.getActivity(), "支付取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void getOrderPayStatus(String orderId) {
        QMUITipDialog dialog = RxUtil.showLoading(mRootView.getActivity(), "请稍后···");
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("orderId", orderId);
        mModel.getOrderPayStatus(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    dialog.show();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    dialog.dismiss();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<OrderPayStatus>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<OrderPayStatus> commonData) {
                        if (commonData.isResult()) {
                            if (commonData.getData().getOrderStatus() != 0) {
                                mRootView.showMessage("订单不可支付");
                                mRootView.paySuccess();
                                mRootView.killMyself();
                            }
                        }
                    }
                });
    }

}
